//
//  RHDeviceSecretVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/5/22.
//

#import "RHDeviceSecretVC.h"
#import "RHTools.h"

@interface RHDeviceSecretVC ()
@property (nonatomic, strong) UIImageView *qrCodeImageView;

@property (nonatomic, strong) UIImageView *iconImageView;

@property (nonatomic, strong) QMUILabel *titleLab;

@property (nonatomic, strong) QMUILabel *secretLab;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) QMUIButton *saveBtn;

@property (nonatomic ,copy) NSString *secret;
@end

@implementation RHDeviceSecretVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"设备密钥".rh_localized;
    [self setupUI];
    [self getDeviceSecret];
}

-(void)setupUI
{
    kWeakSelf;
    
    
    
    
    UIView *bgView = kView;
    bgView.backgroundColor = UIColor.whiteColor;
    [bgView rounded:8 width:1 color:kBorderColor];
    [self.view addSubview:bgView];
    self.bgView = bgView;
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.equalTo(bgView.mas_width).multipliedBy(1.1);
    }];
    
    QMUIButton *saveBtn = [[QMUIButton alloc]init];
    saveBtn.layer.cornerRadius = 8;
    saveBtn.layer.masksToBounds = YES;
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn setTitle:@"保存到相册".rh_localized forState:UIControlStateNormal];
    [saveBtn setImage:[UIImage imageNamed:@"device_secret_download"] forState:UIControlStateNormal];
    saveBtn.imagePosition = QMUIButtonImagePositionLeft;
    saveBtn.spacingBetweenImageAndTitle = 10;
    [saveBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:saveBtn];
    self.saveBtn = saveBtn;
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset (15);
        make.right.mas_offset(-15);
        make.top.equalTo(bgView.mas_bottom).offset(20);
        make.height.offset(50);
    }];
    [[saveBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
       UIImage *image = [weakSelf captureImageFromView:weakSelf.bgView];
        UIImageWriteToSavedPhotosAlbum(image, weakSelf, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];
    
    //
    self.titleLab = [[QMUILabel alloc]init];
    self.titleLab.font = [UIFont systemFontOfSize:18];
    self.titleLab.numberOfLines = 0;
    self.titleLab.textAlignment = NSTextAlignmentCenter;
    self.titleLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:1];
    self.titleLab.text = [NSString stringWithFormat:@"%@%@",self.deviceId,@"设备密钥二维码".rh_localized];
    [bgView addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(35);
    }];
    
    
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"#EBEDF0");
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(weakSelf.titleLab.mas_bottom).offset(35);
        make.height.offset(1);
    }];
    
    UIImageView *qrBgImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@""]];//框框
    qrBgImg.backgroundColor = CFTabViewBgColor;
    qrBgImg.layer.cornerRadius = 8;
    qrBgImg.layer.masksToBounds = YES;
    [bgView addSubview:qrBgImg];
    [qrBgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kScaleW(180));
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(0);
    }];
    
    self.qrCodeImageView = [[UIImageView alloc]init];
    [qrBgImg addSubview:self.qrCodeImageView];
    [self.qrCodeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(15, 15, 15, 15));
    }];
    
    UIImageView *qrSecretIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"device_secret_icon"]];
    [qrBgImg addSubview:qrSecretIcon];
    [qrSecretIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(25);
        make.center.mas_offset(0);
    }];
    
    UIView *secretView = kView;
    [bgView addSubview:secretView];
    [secretView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(qrBgImg.mas_bottom).offset(25);
        make.centerX.mas_offset(0);
        make.width.lessThanOrEqualTo(@(kUI_WINDOW_W-80));
    }];
    //
    self.secretLab = [[QMUILabel alloc]init];
    self.secretLab.font = [UIFont systemFontOfSize:14];
    self.secretLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:0.8];
    self.secretLab.text = [NSString stringWithFormat:@"%@: %@",@"设备密钥".rh_localized,self.secret];
    [secretView addSubview:self.secretLab];
    [self.secretLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.top.mas_offset(10);
        make.bottom.mas_offset(-10);
    }];
    
    QMUIButton *copyBtn = [[QMUIButton alloc]init];
    [copyBtn setImage:[UIImage imageNamed:@"device_secret_copy"] forState:UIControlStateNormal];
    [secretView addSubview:copyBtn];
    [copyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(35);
        make.right.mas_offset(-15);
        make.left.equalTo(weakSelf.secretLab.mas_right).offset(10);
    }];
    
    
    
    
    
    [[copyBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = weakSelf.secret;
        [QMUITips showSucceed:@"已复制".rh_localized];
    }];
}

#pragma mark ---- 截屏
-(UIImage *)captureImageFromView:(UIView *)view

{
    self.saveBtn.hidden = YES;
    CGRect imageRectInPDF = CGRectMake(0, 0, view.width*2, view.height*2);

    UIGraphicsImageRenderer *imageRender = [[UIGraphicsImageRenderer alloc]initWithSize:view.size];
    UIImage *chart_Image = [imageRender imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
        [self.bgView.layer renderInContext:rendererContext.CGContext];
    }];
    UIGraphicsBeginImageContext(CGSizeMake(imageRectInPDF.size.width, imageRectInPDF.size.height));
    [chart_Image drawInRect:CGRectMake(0, 0, imageRectInPDF.size.width, imageRectInPDF.size.height)];
    //将图片放大,填满pdf
    UIImage *image_scale = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.saveBtn.hidden = NO;
    //用这个方法图片就模糊
//    CGRect screenRect = CGRectMake(0, 0, view.width, view.height);
//
//    UIGraphicsBeginImageContext(screenRect.size);
//
//    CGContextRef ctx = UIGraphicsGetCurrentContext();
//
//    [view.layer renderInContext:ctx];
//
//    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
//
//    UIGraphicsEndImageContext();

    return image_scale;

}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *title = @"";
    NSString *message = @"";
    if (!error) {
           title = @"保存成功".rh_localized;
           message = @"前往相册查看?".rh_localized;
    }else {
           title = @"保存失败".rh_localized;
           message = @"";
    }
       
    // 使用alert view显示二维码保存状态
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:@"photos-redirect://"];
        if([[UIApplication sharedApplication] canOpenURL:url]){
           [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
         }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];

}

-(void)getDeviceSecret
{
    //从后台获取设备秘钥
   
    [BaseModel startGetWithCompletionAPIKey:H_getDevicePassword argument:@{@"deviceId":ValidNullData(self.deviceId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSString *pwd = ValidNullData(request.responseJSONObject[@"data"][@"password"]);
            self.secret = [NSString  base64Decode:pwd];
            self.secretLab.text = [NSString stringWithFormat:@"%@: %@",@"设备密钥".rh_localized,self.secret];
            [self genarateQRCodeWithContent:pwd];
        }
        
                
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
 
}



//终端用户本地生成二维码,用于电站转让直接扫描
-(void)createInviationCode
{
    NSString *email = [PrivateMange share].currentUser.email;
    NSDictionary *emailDic = @{@"email":email};
    NSData *data = [[emailDic yy_modelToJSONString] dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64Str = [data base64EncodedStringWithOptions:0];
    [self genarateQRCodeWithContent:base64Str];
    
}

/**
  *  根据CIImage生成指定大小的UIImage
  *
 *  @param image CIImage
 *  @param size  图片宽度
  */
 - (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
     CGRect extent = CGRectIntegral(image.extent);
     CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
     // 1.创建bitmap;
     size_t width = CGRectGetWidth(extent) * scale;
   size_t height = CGRectGetHeight(extent) * scale;
     CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
     CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
     CIContext *context = [CIContext contextWithOptions:nil];
     CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
     CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
     CGContextScaleCTM(bitmapRef, scale, scale);
     CGContextDrawImage(bitmapRef, extent, bitmapImage);

     // 2.保存bitmap到图片
     CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
     CGContextRelease(bitmapRef);
     CGImageRelease(bitmapImage);
     return [UIImage imageWithCGImage:scaledImage];
 }

#pragma mark ------- 生成二维码 -------
-(void)genarateQRCodeWithContent:(NSString*)content
{
    if(content.length == 0)return;
    
    NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];
    
//    CIFilter* color_filter = [CIFilter filterWithName:@"CIFalseColor"];
//
//    [color_filter setDefaults];
//
//    [color_filter setValue:filter.outputImage forKey:@"inputImage"];
//
//    //设置二维码的颜色（二维码都是由2个颜色组成，可自行改变尝试效果）
//
//    [color_filter setValue:[CIColor colorWithRed:86/255.0 green:194/255.0 blue:113/255.0] forKey:@"inputColor0"];
//
//    [color_filter setValue:[CIColor greenColor]forKey:@"inputColor1"];

    
    UIImage *image = [self createNonInterpolatedUIImageFormCIImage:filter.outputImage withSize:150];
    
    UIImage *logo = [UIImage imageNamed:@"device_sceret"];
    
    UIImage *logoQRImage = [self addLogo:image logo:logo];
    
    self.qrCodeImageView.image = logoQRImage;
}


//二维码中间插入小插图
-(UIImage*)addLogo:(UIImage *)ori_img logo:(UIImage*)logo_img
{
    UIGraphicsBeginImageContextWithOptions(ori_img.size,NO,[[UIScreen mainScreen]scale]);
    //将二维码的图片画入
    [ori_img drawInRect:CGRectMake(0, 0, ori_img.size.width, ori_img.size.height)];
    
    UIImage *centerImg = logo_img;
    
    CGFloat centerW = ori_img.size.width*0.3;
    
    CGFloat centerH = centerW;
    
    CGFloat centerX = (ori_img.size.width-centerW)*0.5;
    
    CGFloat centerY = (ori_img.size.height-centerH)*0.5;
    
    [centerImg drawInRect:CGRectMake(centerX, centerY, centerW, centerH)];
   
    //5.3获取绘制好的图片
    
    UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
    
    //5.4关闭图像上下文
    
    UIGraphicsEndImageContext();
    
    return finalImg;
    
}

@end
